package com.web.action;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mysql.jdbc.StringUtils;
import com.web.action.res.Response;
import com.web.action.res.ResponseData;
import com.web.common.Sys;
import com.web.model.PageBean;
import com.web.model.RefreshUser;
import com.web.model.TCathectic;
import com.web.model.TDict;
import com.web.model.TUser;
import com.web.model.TUserBalanceRecord;
import com.web.model.TWinNum;
import com.web.model.constant.Constant;
import com.web.service.TCathecticService;
import com.web.service.TDictService;
import com.web.service.TUserBalanceRecordService;
import com.web.service.TUserService;
import com.web.service.TWinNumService;
import com.web.utils.MD5;
import com.web.utils.WebUtil;

@Controller
@RequestMapping("user")
public class TUserAction {

	@Autowired
	private TUserService userService;

	@Autowired
	private TDictService tDictService;

	@Autowired
	private TWinNumService tWinNumService;

	@Autowired
	private TCathecticService catecticService;

	@Autowired
	private TUserBalanceRecordService userBalanceRecordService;

	@Resource(name = "sys")
	private Sys sys;

	private static SimpleDateFormat dayFmarter = new SimpleDateFormat("yyyy-MM-dd");

	/* 新增会员 */
	@RequestMapping(value = "add_user", method = RequestMethod.GET)
	public String toAddUser(HttpSession session) {
		TUser u = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (u == null) {
			return "login";
		} else if (u.getRoleId() != null && u.getRoleId() == 3) {
			return "login";
		}
		return "add_user";
	}

	/* 新增用户 */
	@RequestMapping(value = "add_user", method = RequestMethod.POST)
	@ResponseBody
	public Response addUser(TUser user, HttpServletRequest request, HttpSession session) {
		Response res = new Response();
		TUser u = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (u == null) {
			return res.TokenInvalid;
		}
		if (StringUtils.isNullOrEmpty(user.getUserNo()) || StringUtils.isNullOrEmpty(user.getPassword())) {
			return res.ParamError;
		}

		TUser userParam = new TUser();
		userParam.setUserNo(user.getUserNo());
		TUser hasUser = userService.selectByModelSelective(userParam);
		if (hasUser != null) {
			return res.UserExists;
		}
		// 如果是新增普通用户得设置他的上级
		// Long roleId = user.getRoleId();
		user.setParentUserId(u.getUserId());
		userService.insert(user);
		return res.SUCC;
	}

	/* 用户注销 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView logout(HttpServletRequest request, HttpSession session) {
		ModelAndView mv = new ModelAndView();

		session.removeAttribute(Constant.SESSION_USER);
		session.removeAttribute(Constant.SESSION_UID);
		session.removeAttribute(Constant.SESSION_TOKEN);
		session.invalidate();

		mv.setViewName("redirect:/user/login");
		return mv;
	}

	/* 跳转登录页面 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView loginJsp(HttpServletRequest request, HttpSession session) {
		ModelAndView mv = new ModelAndView();
		// 校验是否合法来源
		String token = (String) session.getAttribute(Constant.SESSION_TOKEN);
		if (WebUtil.isEmpty(token)) {
			mv.setViewName("redirect:/index");
		} else {
			mv.setViewName("/login");
		}
		return mv;
	}

	/* 系统登录 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Response login(TUser user, String captcha, HttpServletRequest request, HttpSession session) {
		Response res = new Response();
		if (StringUtils.isNullOrEmpty(user.getUserNo())) {
			return res.UserNoIsNull;
		} else if (StringUtils.isNullOrEmpty(user.getPassword())) {
			return res.PasswordIsNull;
		} else if (StringUtils.isNullOrEmpty(captcha)) {
			return res.CodeIsNull;
		}

		if (!captcha.equals(session.getAttribute(Response.SESSION_SECURITY_CODE))) {
			return res.CaptchaError;
		}
		TUser resultUser = userService.login(user);
		if (resultUser == null) {
			return res.UserOrPwdInvalid;
		}
		if (resultUser.getUserStatus() != 1) {
			return res.UserIsLock;
		}
		// 线路控制
		if ("1".equals(user.getLoginType()) && resultUser.getRoleId() != 3) {
			return res.ToAgentRoute;
		} else if ("2".equals(user.getLoginType()) && resultUser.getRoleId() == 3) {
			return res.ToUserRoute;
		}
		// 修改用户登录信息
		TUser userParam = new TUser();
		userParam.setIp(WebUtil.getRealIp(request));
		userParam.setLastLoginTime(WebUtil.getDateTimestamp());
		userParam.setUserId(resultUser.getUserId());
		userService.updateByPrimaryKey(userParam);

		// 放session
		resultUser.setPassword(null);// 设置密码为空
		resultUser.setUserBalance(WebUtil.formartDouble(resultUser.getUserBalance(), 2));
		resultUser.setCreditAmt(WebUtil.formartDouble(resultUser.getCreditAmt(), 2));
		session.setAttribute(Constant.SESSION_USER, resultUser);
		return res.SUCC;
	}

	/* 修改用户信息 */
	@RequestMapping(value = "/update_own_user", method = RequestMethod.POST)
	@ResponseBody
	public Response updateOwnUser(TUser user, HttpServletRequest request, HttpSession session) {
		Response res = new Response();
		TUser u = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (u == null) {
			return res.TokenInvalid;
		}
		if (u.getRoleId() != 1) {
			TUser resultUser = userService.selectByPrimaryKey(user.getUserId());
			if (resultUser.getParentUserId() != u.getUserId()) {
				return res.UserNotYours;
			}
			if (!StringUtils.isNullOrEmpty(user.getPassword())) {
				user.setPassword(MD5.encode(user.getPassword()));
			}
			userService.updateByPrimaryKey(user);
		}

		return res.SUCC;
	}

	/* 修改用户密码 */
	@RequestMapping("update_user")
	@ResponseBody
	public Response updateUser(TUser user, HttpServletRequest request) {
		Response res = new Response();
		TUser u = (TUser) request.getSession().getAttribute(Constant.SESSION_USER);
		if (u == null) {
			return res.TokenInvalid;
		}
		if (StringUtils.isNullOrEmpty(user.getPassword()) || StringUtils.isNullOrEmpty(user.getOldPassword())) {
			return res.ParamError;
		}

		TUser ru = userService.selectByPrimaryKey(u.getUserId());
		if (user.getPassword() != null) {
			if (!ru.getPassword().equals(MD5.encode(user.getOldPassword()))) {
				return res.UserOldPwdInvalid;
			}
		}
		user.setUserId(u.getUserId());
		user.setPassword(MD5.encode(user.getPassword()));
		userService.updateByPrimaryKey(user);
		return res.SUCC;
	}

	/* 验证码 */
	@RequestMapping("/verified")
	public void generate(HttpSession session, HttpServletResponse response, HttpServletRequest request) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = WebUtil.getCode(4);
		int width = 90;// 定义图片的width
		int height = 30;// 定义图片的height
		int fontHeight = 20;
		BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics gd = buffImg.getGraphics();
		// 创建一个随机数生成器类
		Random random = new Random();
		// 将图像填充为白色
		gd.setColor(Color.WHITE);
		gd.fillRect(0, 0, width, height);
		// 创建字体，字体的大小应该根据图片的高度来定。
		Font font = new Font("宋体", Font.BOLD, fontHeight);
		// 设置字体。
		gd.setFont(font);
		// 画边框。
		// gd.setColor(Color.BLACK);
		// gd.drawRect(0, 0, width - 1, height - 1);

		// 随机产生40条干扰线，使图象中的认证码不易被其它程序探测到。
		gd.setColor(Color.green);
		for (int i = 0; i < 10; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			gd.drawLine(x, y, x + xl, y + yl);
		}

		// key用于保存随机产生的验证码，以便用户登录后进行验证。
		session.setAttribute(Response.SESSION_SECURITY_CODE, code);
		int red = 0, green = 0, blue = 0;

		// 随机产生codeCount数字的验证码。
		gd.setColor(new Color(red, green, blue));
		gd.drawString(code, 22, 25);
		// 将四位数字的验证码保存到Session中。

		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		// 将图像输出到Servlet输出流中。
		try {
			ServletOutputStream out = response.getOutputStream();
			ImageIO.write(buffImg, "jpeg", out);

			output.writeTo(out);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/* 用户列表 */
	@RequestMapping(value = "/user_list", method = RequestMethod.GET)
	@ResponseBody
	public ModelAndView queryUserList(TUser user, HttpServletRequest request, HttpSession session) {
		ModelAndView mv = new ModelAndView();
		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			mv.setViewName("redirect:/user/login");
			return mv;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		if (sessionUser.getRoleId() == 2) { // 代理
			map.put("parentUserId", sessionUser.getUserId());
		} else if (sessionUser.getRoleId() == 3) { // 会员
			map.put("userId", sessionUser.getUserId());
		}
		String page = (request.getParameter("page") == null ? "1" : request.getParameter("page"));
		map.put("pageNum", Integer.parseInt(page));
		map.put("pageSize", 10);
		map.put("sort", "create_time");

		PageBean<TUser> userList = userService.selectListByPage(map);

		userList.setUrl("/user/user_list?page=");
		userList.getPageStr();
		mv.addObject("userList", userList);
		mv.setViewName("/user_list");
		return mv;
	}

	/* 新闻中心 */
	@RequestMapping(value = "news", method = RequestMethod.GET)
	public String news() {
		return "news";
	}

	/* 个人资料 */
	@RequestMapping(value = "user_info", method = RequestMethod.GET)
	public String user_info(HttpServletRequest request, HttpSession session) {
		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			return "login";
		}
		TUser user = userService.selectByPrimaryKey(sessionUser.getUserId());
		request.setAttribute("user", user);
		return "user_info";
	}

	/* 北京赛车游戏规则 */
	@RequestMapping(value = "pk_rule", method = RequestMethod.GET)
	public String pk_rule() {
		return "rule";
	}

	/* 帐户历史 */
	@RequestMapping(value = "user_history", method = RequestMethod.GET)
	public String user_history(Long userId, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			return "login";
		}
		Map<String, Object> param = new HashMap<String, Object>();

		TUser resultUser = userService.selectByPrimaryKey(userId);
		if (resultUser == null) {
			param.put("userId", sessionUser.getUserId());
		} else if ((userId != null && resultUser.getParentUserId() == sessionUser.getUserId())
				|| sessionUser.getRoleId() == 1) {
			param.put("userId", userId);
		} else {
			param.put("userId", sessionUser.getUserId());
		}

		String page = (request.getParameter("page") == null ? "1" : request.getParameter("page"));
		param.put("pageNum", Integer.parseInt(page));
		param.put("pageSize", 20);
		PageBean<TUserBalanceRecord> pageBean = userBalanceRecordService.selectUserBalacneList(param);
		pageBean.setUrl("/user/user_history?page=");
		pageBean.getPageStr();
		request.setAttribute("pageBean", pageBean);
		return "user_history";
	}

	/* 开奖结果 */
	@RequestMapping(value = "winning", method = RequestMethod.GET)
	public String winning() {
		return "winning";
	}

	/* 个人资讯 */
	@RequestMapping(value = "user_news", method = RequestMethod.GET)
	public String user_news() {
		return "user_news";
	}

	/* 下注情况 */
	@RequestMapping(value = "user_tz", method = RequestMethod.GET)
	public String user_tz(HttpServletRequest request, HttpSession session) {
		try {

			TUser u = (TUser) request.getSession().getAttribute(Constant.SESSION_USER);
			if (u == null) { // 用户未登录
				return "login";
			}
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("createUser", u.getUserId());
			String page = (request.getParameter("page") == null ? "1" : request.getParameter("page"));
			param.put("pageNum", Integer.parseInt(page));
			param.put("pageSize", 20);
			PageBean<TCathectic> pageBean = catecticService.selectListByPage(param);

			List<TCathectic> list = pageBean.getList();
			double sumTzAmt = 0.00;
			double sumWinAmt = 0.00;
			TDict dict = null;
			for (TCathectic cathectic : list) {
				sumTzAmt = sumTzAmt + cathectic.getCathecticInt();
				sumWinAmt = sumWinAmt + cathectic.getWinAmt();
				dict = sys.getDict(cathectic.getCathecticType() + "-" + cathectic.getCathecticCode());
				cathectic.setCathecticCodeStr(dict.getDictName());
			}
			pageBean.setList(list);
			pageBean.setUrl("/user/user_tz?page=");
			pageBean.getPageStr();
			request.setAttribute("sumTzAmt", WebUtil.formartDouble(sumTzAmt, 2));
			request.setAttribute("sumWinAmt", WebUtil.formartDouble(sumWinAmt, 2));
			request.setAttribute("pageBean", pageBean);
			return "user_tz";
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/* 修改密码 */
	@RequestMapping(value = "password", method = RequestMethod.GET)
	public String password() {
		return "password";
	}

	/* 两面盘 */
	@RequestMapping(value = "double_disc", method = RequestMethod.GET)
	public String double_disc(HttpServletRequest request, HttpSession session) {

		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			return "login";
		}

		request.setAttribute("win", sys.getLastWinNum());
		if (!sys.isOpen()) {
			return "web_stop";
		}

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("sort", "dict_id");
		param.put("order", Constant.ORDER_ASC);
		param.put("dictKey", "PK_CAT_IND");
		param.put("dictType", "01");
		List<TDict> dictList_1 = tDictService.selectList(param);
		request.setAttribute("dictList_1", dictList_1);

		param.put("dictType", "02");
		List<TDict> dictList_2 = tDictService.selectList(param);
		request.setAttribute("dictList_2", dictList_2);

		param.put("dictType", "03");
		List<TDict> dictList_3 = tDictService.selectList(param);
		request.setAttribute("dictList_3", dictList_3);

		param.put("dictType", "04");
		List<TDict> dictList_4 = tDictService.selectList(param);
		request.setAttribute("dictList_4", dictList_4);

		param.put("dictType", "05");
		List<TDict> dictList_5 = tDictService.selectList(param);
		request.setAttribute("dictList_5", dictList_5);

		param.put("dictType", "06");
		List<TDict> dictList_6 = tDictService.selectList(param);
		request.setAttribute("dictList_6", dictList_6);

		param.put("dictType", "07");
		List<TDict> dictList_7 = tDictService.selectList(param);
		request.setAttribute("dictList_7", dictList_7);

		param.put("dictType", "08");
		List<TDict> dictList_8 = tDictService.selectList(param);
		request.setAttribute("dictList_8", dictList_8);

		param.put("dictType", "09");
		List<TDict> dictList_9 = tDictService.selectList(param);
		request.setAttribute("dictList_9", dictList_9);

		param.put("dictType", "10");
		List<TDict> dictList_10 = tDictService.selectList(param);
		request.setAttribute("dictList_10", dictList_10);

		param.put("dictType", "11");
		List<TDict> dictList_11 = tDictService.selectList(param);
		request.setAttribute("dictList_11", dictList_11);

		// 初始化计算封盘时间
		long nextFPMsec = sys.getDistanceSealTime();
		// long nextFPMsec = 212123;
		request.setAttribute("nextFPMsec", nextFPMsec);
		// System.out.println("封盘时间" + nextFPMsec);

		// 距离下次开奖时间毫秒数
		long nextKJMsec = sys.getDistanceOpenTime();
		// long nextKJMsec = 90000;
		request.setAttribute("nextKJMsec", nextKJMsec);
		// System.out.println("开奖时间" + nextKJMsec);

		// 计算两面长龙
		List<TDict> longList = sys.getTopDictList();
		request.setAttribute("longList", longList);
		return "double";
	}

	/* 盘1-5 */
	@RequestMapping(value = "double_1_5", method = RequestMethod.GET)
	public String double_1_5(HttpServletRequest request, HttpSession session) {

		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			return "login";
		}

		request.setAttribute("win", sys.getLastWinNum());
		if (!sys.isOpen()) {
			return "web_stop";
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("sort", "dict_id");
		param.put("order", Constant.ORDER_ASC);
		param.put("dictKey", "PK_CAT_IND");
		param.put("dictType", "01");
		List<TDict> dictList_1 = tDictService.selectList(param);
		request.setAttribute("dictList_1", dictList_1);

		param.put("dictType", "02");
		List<TDict> dictList_2 = tDictService.selectList(param);
		request.setAttribute("dictList_2", dictList_2);

		param.put("dictType", "03");
		List<TDict> dictList_3 = tDictService.selectList(param);
		request.setAttribute("dictList_3", dictList_3);

		param.put("dictType", "04");
		List<TDict> dictList_4 = tDictService.selectList(param);
		request.setAttribute("dictList_4", dictList_4);

		param.put("dictType", "05");
		List<TDict> dictList_5 = tDictService.selectList(param);
		request.setAttribute("dictList_5", dictList_5);

		// 初始化计算封盘时间
		long nextFPMsec = sys.getDistanceSealTime();
		// long nextFPMsec = 212123;
		request.setAttribute("nextFPMsec", nextFPMsec);
		// System.out.println("封盘时间" + nextFPMsec);

		// 距离下次开奖时间毫秒数
		long nextKJMsec = sys.getDistanceOpenTime();
		// long nextKJMsec = 90000;
		request.setAttribute("nextKJMsec", nextKJMsec);
		// System.out.println("开奖时间" + nextKJMsec);

		// 计算两面长龙
		List<TDict> longList = sys.getTopDictList();
		request.setAttribute("longList", longList);

		return "double_1_5";
	}

	/* 盘6-10 */
	@RequestMapping(value = "double_6_10", method = RequestMethod.GET)
	public String double_6_10(HttpServletRequest request, HttpSession session) {

		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			return "login";
		}
		request.setAttribute("win", sys.getLastWinNum());
		if (!sys.isOpen()) {
			return "web_stop";
		}

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("sort", "dict_id");
		param.put("order", Constant.ORDER_ASC);
		param.put("dictKey", "PK_CAT_IND");
		param.put("dictType", "06");
		List<TDict> dictList_6 = tDictService.selectList(param);
		request.setAttribute("dictList_6", dictList_6);

		param.put("dictType", "07");
		List<TDict> dictList_7 = tDictService.selectList(param);
		request.setAttribute("dictList_7", dictList_7);

		param.put("dictType", "08");
		List<TDict> dictList_8 = tDictService.selectList(param);
		request.setAttribute("dictList_8", dictList_8);

		param.put("dictType", "09");
		List<TDict> dictList_9 = tDictService.selectList(param);
		request.setAttribute("dictList_9", dictList_9);

		param.put("dictType", "10");
		List<TDict> dictList_10 = tDictService.selectList(param);
		request.setAttribute("dictList_10", dictList_10);

		// 初始化计算封盘时间
		long nextFPMsec = sys.getDistanceSealTime();
		// long nextFPMsec = 212123;
		request.setAttribute("nextFPMsec", nextFPMsec);
		// System.out.println("封盘时间" + nextFPMsec);

		// 距离下次开奖时间毫秒数
		long nextKJMsec = sys.getDistanceOpenTime();
		// long nextKJMsec = 90000;
		request.setAttribute("nextKJMsec", nextKJMsec);
		// System.out.println("开奖时间" + nextKJMsec);
		// 计算两面长龙
		List<TDict> longList = sys.getTopDictList();
		request.setAttribute("longList", longList);

		return "double_6_10";
	}

	/* 冠亚组合 */
	@RequestMapping(value = "double_group", method = RequestMethod.GET)
	public String double_group(HttpServletRequest request, HttpSession session) {

		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		// 未登陆
		if (sessionUser == null) {
			return "select_line";
		}
		// 非会员跳往代理首页
		if (sessionUser.getRoleId().longValue() != 3) {
			return "/manage/index";
		}

		// 封盘期间24:00-9:00
		request.setAttribute("win", sys.getLastWinNum());
		if (!sys.isOpen()) {
			return "web_stop";
		}

		// 查询当前期次及时间
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("limitIndex", 0);
		map.put("limitSize", 1);
		List<TWinNum> winList = tWinNumService.selectList(map);
		TWinNum win = null;
		if (winList != null && winList.size() > 0) {
			win = winList.get(0);
		}

		// 初始化计算封盘时间
		long nextFPMsec = sys.getDistanceSealTime();
		// long nextFPMsec = 212123;
		request.setAttribute("nextFPMsec", nextFPMsec);
		// System.out.println("封盘时间" + nextFPMsec);

		// 距离下次开奖时间毫秒数
		long nextKJMsec = sys.getDistanceOpenTime();
		// long nextKJMsec = 90000;
		request.setAttribute("nextKJMsec", nextKJMsec);
		// System.out.println("开奖时间" + nextKJMsec);

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("sort", "dict_id");
		param.put("order", Constant.ORDER_ASC);
		param.put("dictKey", "PK_CAT_IND");
		param.put("dictType", "11");
		List<TDict> dictList = tDictService.selectList(param);

		// List<TDict> tmpList = sys.getDictList();
		// List<TDict> dictList = new ArrayList<>();
		// for (TDict d : tmpList) {
		// if ("11".equals(d.getDictType())) {
		// dictList.add(d);
		// }
		// }
		request.setAttribute("dictList", dictList);

		// 缓存获取两面长龙
		List<TDict> longList = sys.getTopDictList();
		request.setAttribute("longList", longList);

		return "double_group";
	}

	@RequestMapping(value = "user_balance_record", method = RequestMethod.GET)
	public String userBalanceRecord(Long userId, HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			return "login";
		}
		Map<String, Object> param = new HashMap<String, Object>();

		TUser resultUser = userService.selectByPrimaryKey(userId);
		if (resultUser == null) {
			param.put("userId", sessionUser.getUserId());
		} else if ((userId != null && resultUser.getParentUserId() == sessionUser.getUserId())
				|| sessionUser.getRoleId() == 1) {
			param.put("userId", userId);
		} else {
			param.put("userId", sessionUser.getUserId());
		}

		String page = (request.getParameter("page") == null ? "1" : request.getParameter("page"));
		param.put("pageNum", Integer.parseInt(page));
		param.put("pageSize", 10);
		PageBean<TUserBalanceRecord> pageBean = userBalanceRecordService.selectUserBalacneList(param);
		pageBean.setUrl("/user/user_balance_record?page=");
		pageBean.getPageStr();
		request.setAttribute("pageBean", pageBean);
		return "user_balance";
	}

	/**
	 * 刷新当期用户信息
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 */
	@RequestMapping("refresh_user")
	@ResponseBody
	public ResponseData<RefreshUser> refreshUser(HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		ResponseData<RefreshUser> res = new ResponseData<RefreshUser>();
		TUser u = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (u == null) {
			res.setResultCode("5");
			res.setMsg("用户登录失效，请重新登录");
			return res;
		}
		RefreshUser refreshUser = new RefreshUser();
		TUser resultUser = userService.selectByPrimaryKey(sessionUser.getUserId());
		if (resultUser == null) {
			res.setResultCode("5");
			res.setMsg("用户登录失效，请重新登录");
			return res;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("createUser", sessionUser.getUserId());
		param.put("todayStart", dayFmarter.format(new Date()) + " 00:00:00");
		param.put("todayEnd", dayFmarter.format(new Date()) + " 23:59:59");
		Double todayWin = catecticService.selectTodayWin(param);

		refreshUser.setUserId(resultUser.getUserId());
		refreshUser.setUserBalance(WebUtil.formartDouble(resultUser.getUserBalance(), 2));// 账户余额

		// 刷新session刘梅提的缺陷
		sessionUser.setUserBalance(refreshUser.getUserBalance());
		session.setAttribute(Constant.SESSION_USER, sessionUser);

		refreshUser.setUserNo(resultUser.getUserNo());
		refreshUser.setTodayWin(todayWin == null ? 0 : todayWin);// 今日输赢金额
		refreshUser.setTodayWin(WebUtil.formartDouble(refreshUser.getTodayWin(), 2));
		res.setResultCode("0");
		res.setMsg("成功");
		res.setData(refreshUser);
		return res;
	}

	@RequestMapping(value = "user_catectic_list", method = RequestMethod.GET)
	public String userCatecticList(Long userId, Integer page, HttpServletRequest request, HttpSession session) {
		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			return "login";
		}
		Map<String, Object> param = new HashMap<String, Object>();
		PageBean<TCathectic> pageBean;
		TUser resultUser = userService.selectByPrimaryKey(userId);
		if (resultUser == null
				|| (sessionUser.getRoleId() != 1 && !resultUser.getParentUserId().equals(sessionUser.getUserId()))) {
			pageBean = new PageBean<TCathectic>(null);
		} else {
			page = page == null ? 0 : page;
			param.put("pageNum", page);
			param.put("pageSize", 10);
			param.put("todayStart", dayFmarter.format(new Date()) + " 00:00:00");
			param.put("todayEnd", dayFmarter.format(new Date()) + " 23:59:59");

			// param.put("todayStart", "2016-12-07 00:00:00");
			// param.put("todayEnd", "2016-12-07 23:59:59");
			param.put("createUser", userId);
			pageBean = catecticService.selectCatheticPageByDay(param);
			List<TCathectic> clist = new ArrayList<TCathectic>();
			for (TCathectic c : pageBean.getList()) {
				c.setDictName(sys.getDict(c.getCathecticType() + "-" + c.getCathecticCode()).getDictName());
				clist.add(c);
			}
			pageBean.setList(clist);
			pageBean.setUrl("/user/user_catectic_list?userId=" + userId + "&page=");
			pageBean.getPageStr();
		}
		request.setAttribute("pageBean", pageBean);

		return "manage/user_catectic_list";
	}

	@RequestMapping(value = "del_user", method = RequestMethod.POST)
	@ResponseBody
	public Response delUser(Long userId, HttpServletRequest request, HttpSession session) {
		Response res = new Response();
		TUser sessionUser = (TUser) session.getAttribute(Constant.SESSION_USER);
		if (sessionUser == null) {
			return res.TokenInvalid;
		}
		TUser resultUser = userService.selectByPrimaryKey(userId);
		if (resultUser == null) {
			return res.UserNotExists;
		}
		if (!resultUser.getParentUserId().equals(sessionUser.getUserId())) {
			return res.UserNotYours;
		}
		userService.deleteAllByUserId(userId);
		return res.SUCC;
	}

}
